import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:sjx/constants.dart';
import 'package:sjx/pages/login/login_vm.dart';
import 'package:sjx/route/routes.dart';

import '../../route/route_utils.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  late final viewModel = LoginViewModel();

  @override
  void initState() {
    super.initState();
    viewModel.setOnLoginSuccess(() {
      RouteUtils.pushNamedAndRemoveUntil(context, RoutePath.tab);
    });
  }

  void _openPrivacyPolicy(BuildContext context) {
    // 打开隐私协议页面
    RouteUtils.pushForNamed(context, RoutePath.web_view, arguments: {'url': Constants.Privacy_Protocol});
  }

  void _openUserAgreement(BuildContext context) {
    // 打开用户协议页面
    RouteUtils.pushForNamed(context, RoutePath.web_view, arguments: {'url': Constants.Server_Protocol});
  }

  void _getVerificationCode() {
    viewModel.getPhoneCode();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
        create: (context){
          return viewModel;
        },
        child: Consumer<LoginViewModel>(builder: (context, value, child) {
          bool _isAgreed = value.isAgreed;
          return Scaffold(
            appBar: AppBar(
              leading: IconButton(
                icon: const Icon(Icons.arrow_back, color: Colors.black),
                onPressed: () => Navigator.pop(context),
              ),
              backgroundColor: Colors.white,
              elevation: 0,
            ),
            backgroundColor: Colors.white,
            body: SafeArea(
              child: Stack(
                children: [
                  SingleChildScrollView(
                    padding: EdgeInsets.symmetric(horizontal: 24.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(height: 8.h),
                        Text(
                          'Hi, 欢迎来到赏金侠',
                          style: TextStyle(
                            fontSize: 24.sp,
                            fontWeight: FontWeight.bold,
                            color: Colors.black,
                          ),
                        ),
                        SizedBox(height: 8.h),
                        Text(
                          '无需注册，手机号可直接登录',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.grey[600],
                          ),
                        ),
                        SizedBox(height: 40.h),

                        // 手机号输入框
                        Container(
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey[300]!),
                            borderRadius: BorderRadius.circular(8.r),
                          ),
                          child: Row(
                            children: [
                              Padding(
                                padding: EdgeInsets.symmetric(horizontal: 12.w),
                                child: Text(
                                  '手机号',
                                  style: TextStyle(
                                    fontSize: 16.sp,
                                    color: Colors.black,
                                  ),
                                ),
                              ),
                              Expanded(
                                child: TextField(
                                  decoration: InputDecoration(
                                    border: InputBorder.none,
                                    hintText: '请输入您的手机号',
                                    hintStyle: TextStyle(
                                      fontSize: 16.sp,
                                      color: Colors.grey[400],
                                    ),
                                    contentPadding: EdgeInsets.symmetric(vertical: 16.h),
                                  ),
                                  keyboardType: TextInputType.phone,
                                  onChanged: (value) {
                                    viewModel.updatePhoneNumber(value);
                                  },
                                ),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(height: 16.h),

                        // 验证码输入框
                        Container(
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey[300]!),
                            borderRadius: BorderRadius.circular(8.r),
                          ),
                          child: Row(
                            children: [
                              Padding(
                                padding: EdgeInsets.symmetric(horizontal: 12.w),
                                child: Text(
                                  '验证码',
                                  style: TextStyle(
                                    fontSize: 16.sp,
                                    color: Colors.black,
                                  ),
                                ),
                              ),
                              Expanded(
                                child: TextField(
                                  decoration: InputDecoration(
                                    border: InputBorder.none,
                                    hintText: '请输入验证码',
                                    hintStyle: TextStyle(
                                      fontSize: 16.sp,
                                      color: Colors.grey[400],
                                    ),
                                    contentPadding: EdgeInsets.symmetric(vertical: 16.h),
                                  ),
                                  keyboardType: TextInputType.number,
                                  onChanged: (value) {
                                    viewModel.updateCodeNumber(value);
                                  },
                                ),
                              ),
                              // 添加获取验证码按钮
                              Padding(
                                padding: EdgeInsets.only(right: 12.w),
                                child: viewModel.isCounting
                                    ? Text(
                                  '${viewModel.countdown}s',
                                  style: TextStyle(
                                    fontSize: 14.sp,
                                    color: Colors.grey,
                                  ),
                                )
                                    : TextButton(
                                  onPressed: _getVerificationCode,
                                  child: Text(
                                    '获取验证码',
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      color: viewModel.isCounting ? Colors.grey : Colors.blue,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(height: 16.h),

                        // 登录按钮
                        SizedBox(
                          width: double.infinity,
                          child: ElevatedButton(
                            onPressed:  () {
                              viewModel.loginPress();
                            } , // 根据协议状态启用/禁用按钮
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Theme.of(context).colorScheme.primary,
                              padding: EdgeInsets.symmetric(vertical: 16.h),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8.r),
                              ),
                            ),
                            child: Text(
                              '登录',
                              style: TextStyle(
                                fontSize: 16.sp,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ),
                        SizedBox(height: 24.h),

                        // 切换登录方式
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            TextButton(
                              onPressed: () {
                                RouteUtils.pushForNamed(context, RoutePath.login_password);
                              } ,
                              child: Text(
                                '密码登录',
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color:  Colors.blue ,
                                ),
                              ),
                            ),
                            SizedBox(width: 16.w),
                            TextButton(
                              onPressed: () {
                                RouteUtils.pushForNamed(context, RoutePath.register);
                              },
                              child: Text(
                                '注册账户',
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: Colors.blue,
                                ),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(height: 80.h), // 为底部协议留出空间
                      ],
                    ),
                  ),
                ],
              ),
            ),
            bottomNavigationBar: SafeArea(
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 16.h),
                  color: Colors.white,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Checkbox(
                        value: _isAgreed,
                        onChanged: (valueEx) {
                          viewModel.setAgreed(valueEx ?? false);
                        },
                        activeColor: Colors.blue,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(4.r),
                        ),
                      ),
                      Expanded(
                        child: RichText(
                          text: TextSpan(
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: Colors.grey[600],
                            ),
                            children: [
                              const TextSpan(text: '我已阅读并同意 '),
                              TextSpan(
                                text: '隐私协议',
                                style: TextStyle(
                                  color: Colors.blue,
                                  decoration: TextDecoration.underline,
                                ),
                                recognizer: TapGestureRecognizer()
                                  ..onTap = () => _openPrivacyPolicy(context),
                              ),
                              const TextSpan(text: ' 和 '),
                              TextSpan(
                                text: '用户协议',
                                style: TextStyle(
                                  color: Colors.blue,
                                  decoration: TextDecoration.underline,
                                ),
                                recognizer: TapGestureRecognizer()
                                  ..onTap = () => _openUserAgreement(context),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                )
            ),
          );
        }),
    );
  }
}